#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys, datetime, time, os, logging
import ibm_db
import re
import json
from apscheduler.schedulers.blocking import BlockingScheduler

from config import app_config, ProductionConfig, DevelopmentConfig

from app.utils.XUtils import XUtils
from app.utils.XLogger import XLogger
from app.TestStateJob import TestStateJob
from app.FDCLStateJob import FDCLStateJob
from app.RCMStateJob import RCMStateJob
from app.ColdRollingJob import ColdRollingJob
from app.ColdRollingJob3 import ColdRollingJob3

from app.utils.XDB2Utils import XDB2Utils


def main(p_argv):
    profile = p_argv[1] if len(p_argv) > 1 else 'dev'
    run_immediately = True if len(p_argv) > 2 else False
    #
    config = app_config[profile]
    if os.getenv('DB_HOST') is not None:
        config.DB_HOST = os.environ.get('DB_HOST')
        config.DB_PORT = os.environ.get('DB_PORT')
        config.DB_USER = os.environ['DB_USER']
        config.DB_PASSWORD = os.environ['DB_PASSWORD']
        config.DB_INSTANCE_NAME = os.environ['DB_INSTANCE_NAME']
        config.DB_CHARSET = os.environ['DB_CHARSET']

    # test_db(p_config=config)

    if run_immediately:
        run_job(p_config=config)

    scheduler = BlockingScheduler()
    # NOTE 并行 10分钟一次
    # scheduler.add_job(func=run_job, args=[config], trigger='cron', minute='*/10', id="run_job", max_instances=1,
    #                    next_run_time=datetime.datetime.now())
    # NOTE 每天00:30分执行该定时任务
    scheduler.add_job(func=run_job, args=[config], trigger='cron', day='*', hour='0', minute='30')
    scheduler.start()

    return 0


def run_job(p_config=None):
    ColdRollingJob3(p_config=p_config).execute()
    #
    # for i in range(22, 25):
    #     # 只查一天的数据量可能还好  直接20天  我怕一个高频
    #     # 就是1201-1202  跑完自己跑1202-1203
    #     now = datetime.datetime.now()
    #     max_end_time_1 = datetime.datetime(year=now.year, month=12, day=i, hour=0, minute=0).strftime('%Y%m%d%H%M%S')
    #     max_end_time_2 = datetime.datetime(year=now.year, month=12, day=i + 1, hour=0, minute=0).strftime(
    #         '%Y%m%d%H%M%S')
    #
    #     print(max_end_time_1)
    #     print(max_end_time_2)
    #     print('\n\n\n\n')
    #
    #     ColdRollingJob(p_config=p_config).execute(max_end_time_1=max_end_time_1, max_end_time_2=max_end_time_2)
    pass


if __name__ == '__main__':
    info = XUtils.get_git_info()
    XLogger.instance().logger.info('\n%s' % json.dumps(info, sort_keys=True, indent=4))

    start = datetime.datetime.now()

    status = main(sys.argv)

    elapsed = float((datetime.datetime.now() - start).seconds)
    print("Time Used 4 All ----->>>> %f seconds" % (elapsed))

    sys.exit(status)
